﻿
Imports osi.root.connector
Imports osi.root.formation
Imports osi.root.delegates

Public Class disposer(Of T)
    Inherits pointer(Of T)

    Private ReadOnly disposer As void(Of T) = Nothing

    Public Sub New(ByVal p As _do(Of T),
                   Optional ByVal init As void = Nothing,
                   Optional ByVal disposer As void(Of T) = Nothing)
        assert(Not p Is Nothing)
        If Not init Is Nothing Then
            init()
        End If
        [set](p())
        Me.disposer = disposer
    End Sub

    Public Sub New(ByVal p As T,
                   Optional ByVal init As void = Nothing,
                   Optional ByVal disposer As void(Of T) = Nothing)
        Me.New(Function() p, init, disposer)
    End Sub

    Protected Overridable Sub dispose(ByVal i As T)
        If Not disposer Is Nothing Then
            disposer(i)
        ElseIf TypeOf i Is IDisposable Then
            i.as(Of IDisposable)().Dispose()
        End If
    End Sub

    Protected Sub dispose()
        dispose([get]())
    End Sub
End Class
